const { ccclass, property } = cc._decorator;

@ccclass
export default class SoundMgr extends cc.Component {
    @property
    sound_path: string = 'Sounds';
    @property(cc.Boolean)
    sound_enabled: boolean = false;//是否静音
    @property
    sound_volume: number = 1;//音量
    @property
    music: string = '';//当前播放的音乐
    @property
    type: number = 0;//音频类型 0：按键 1：游戏
    _sounds: { [key: number]: any } = {};

    onLoad() {
        this.loadSounds();
    }
    seting() {
        let date = gameHelper.getInstance().mySetParams;
        if (date?.length > 0) {
            this.sound_enabled = date[this.type].Enabled;
            this.sound_volume = date[this.type].Volume;
        }
    }
    loadSounds() {
        let self = this;
        cc.resources.loadDir(this.sound_path, cc.AudioClip, function (err, clips) {
            for (let i = 0; i < clips.length; i++) {
                self.addSound(clips[i].name, clips[i] as cc.AudioClip);
            }
        });
    }

    addSound(key: string, clip: cc.AudioClip) {
        this._sounds[key] = clip;
    }

    playClick(event, date) {
        this.play(date);
    }

    play(musicName: string, loop: boolean = false) {
        if (musicName) {
            this.seting();
            this.music = musicName;
            if (this.sound_enabled) return;
            cc.audioEngine.setEffectsVolume(this.sound_volume);
            cc.audioEngine.playEffect(this._sounds[musicName], loop);
        }
    }

    stopMusic() {
        cc.audioEngine.stopMusic();
    }

    setEnabled(enabled: boolean) {
        this.sound_enabled = enabled;
        if (this.sound_enabled) {
            this.play(this.music);
        }
        else {
            cc.audioEngine.stopAll();
        }
    }

    getEnable() {
        return this.sound_enabled;
    }
}
